using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using SpoonCore2.Message;

namespace SpoonCore2.Service.Monitor
{
	class MonitorMessage : AbstractMessage
	{
		public enum MessageType : byte { Request, Response }

		private MessageType _type = MessageType.Request;
		private readonly List<RequestItem> _requestData = new List<RequestItem>();
		private readonly SortedList<string, List<MonitorService.MonitorItem>> _data = new SortedList<string, List<MonitorService.MonitorItem>>();

		public MessageType Type
		{
			get { return _type; }
			set { _type = value; }
		}

		public List<RequestItem> Request
		{
			get { return _requestData; }
		}

		public SortedList<string, List<MonitorService.MonitorItem>> Data
		{
			get { return _data; }
		}

		public override void GetBytes(BinaryWriter bw)
		{
			bw.Write((byte)_type);
			
			bw.Write(Request.Count);
			foreach (RequestItem item in Request)
			{
				item.GetBytes(bw);
			}

			bw.Write(Data.Count);
			foreach (string key in Data.Keys)
			{
				bw.Write(key);
				bw.Write(Data[key].Count);
				foreach (MonitorService.MonitorItem item in Data[key])
				{
					item.GetBytes(bw);
				}
			}
		}

		public override void SetBytes(IService service, BinaryReader br)
		{
			_type = (MessageType) br.ReadByte();

			int count = br.ReadInt32();
			while(count > 0)
			{
				Request.Add(new RequestItem(br));
				count--;
			}

			count = br.ReadInt32();
			while(count > 0)
			{
				string key = br.ReadString();
				int count2 = br.ReadInt32();
				List<MonitorService.MonitorItem> items = new List<MonitorService.MonitorItem>();
				while(count2> 0)
				{
					items.Add(new MonitorService.MonitorItem(br));
					count2--;
				}
				Data.Add(key, items);
				count--;
			}
		}

		public class RequestItem
		{
			private string _key;
			private DateTime _start;
			private DateTime _stop;

			public RequestItem(BinaryReader br)
			{
				_key = br.ReadString();
				_start = new DateTime(br.ReadInt64());
				_stop = new DateTime(br.ReadInt64());
			}

			public string Key
			{
				get { return _key; }
				set { _key = value; }
			}

			public DateTime Start
			{
				get { return _start; }
				set { _start = value; }
			}

			public DateTime Stop
			{
				get { return _stop; }
				set { _stop = value; }
			}

			public void GetBytes(BinaryWriter bw)
			{
				bw.Write(_key);
				bw.Write(_start.Ticks);
				bw.Write(_stop.Ticks);
			}
		}
	}
}
